package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用loadUserByUsername()方法获取用户名为【{}】的用户详情...",s);

        AdminLoginInfoVO admin = mapper.getLoginInfoByUsername(s);
        if (admin == null) {
            String message = "登陆失败，用户名不存在！";
            log.warn(message);
            throw new BadCredentialsException("登陆失败，用户名不存在");
        }

//        UserDetails userDetails = User.builder()
//                .username(loginInfoByUsername.getUsername())
//                .password(loginInfoByUsername.getPassword())
//                .disabled(loginInfoByUsername.getEnable() == 0) //账号是否禁用
//                .accountExpired(false) // 账号是否已过期
//                .accountLocked(false) // 账号是否被锁定
//                .credentialsExpired(false) // 凭证是否已过期
//                .authorities("临时设置的权限，暂无意义，避免报错") // 权限，【注意】必须调用
//                .build();

//        GrantedAuthority authority = new SimpleGrantedAuthority("这是一个假权限");
//        authorities.add(authority);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : admin.getPermissions()) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(
                admin.getId(),
                admin.getUsername(),
                admin.getPassword(),
                admin.getEnable() == 1,
                authorities);

        log.debug("即将向Spring Security框架返回UserDetails对象：{}", adminDetails);
        return adminDetails;
    }
}
